package org.infodavid.common.persistence;

import javax.persistence.PersistenceException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.infodavid.common.model.IUserSession;
import org.infodavid.common.persistence.impl.AbstractDataService;
import org.infodavid.common.reflect.InstantiationHelper;

/**
 * The Class UserSessionDataService.
 */
public abstract class UserSessionDataService extends AbstractDataService<IUserSession,String> {

  /** The singleton. */
  private static final UserSessionDataService SINGLETON;

  /** The Constant log. */
  private static final Log LOGGER = LogFactory.getLog(UserSessionDataService.class);

  /** The Constant DEFAULT_USER_SESSION_IDLE_TIME. */
  private static final byte DEFAULT_USER_SESSION_IDLE_TIME = 15;

  /** The Constant USER_SESSION_IDLE_TIME_SYSTEM_PROPERTY. */
  public static final String USER_SESSION_IDLE_TIME_SYSTEM_PROPERTY =
      "org.infodavid.userSessionIdleTimeInMin";

  static {
    try {
      SINGLETON = InstantiationHelper.getInstance().newInstance(UserSessionDataService.class);
    }
    catch (final Exception e) {
      LOGGER.fatal("Can not instantiate the " + UserSessionDataService.class.getName(), e);

      throw new Error(e);
    }
  }

  /**
   * returns the singleton.
   * @return the singletons
   */
  public static UserSessionDataService getInstance() {
    return SINGLETON;
  }

  /**
   * Instantiates a new service.
   */
  protected UserSessionDataService() {
    super();
  }

  /**
   * Gets the user session idle time in minutes.
   * @return the default duration
   */
  public int getSessionIdleTimeInMin() {
    final String value = System.getProperty(USER_SESSION_IDLE_TIME_SYSTEM_PROPERTY);
    int result = DEFAULT_USER_SESSION_IDLE_TIME;

    if (StringUtils.isNotEmpty(value)) {
      try {
        result = Double.valueOf(value).intValue();
      }
      catch (final Exception e) {
        result = -1;
      }
    }

    if (result <= 0) {
      result = DEFAULT_USER_SESSION_IDLE_TIME;
    }

    return result;
  }

  /**
   * Find by user and date.
   * @param session the persistence session
   * @param userKey the user key
   * @return the user session or null
   * @throws PersistenceException the persistence exception
   */
  public abstract IUserSession findLastActiveByUser(PersistenceSession session, Long userKey)
      throws PersistenceException;
}
